import { Text, View, Image, TextInput, StyleSheet, Button, FlatList, Modal, TouchableHighlight, LogBox } from "react-native"
import { useEffect, useState } from "react"
import { useAuth } from '../context/AuthProvider';

const Sale = (props) => {
    // console.log(props.children[6]);
    let btn = props.children[2]
    const navigation = props.children[0]["navigate"]
    // FalList需要更新
    const [refreshing, setRefreshing] = useState(false);
    const [page, setPage] = useState(1);
    // 跟评论有关的东西
    const [text, setText] = useState('')
    const [modalVisible, setModalVisible] = useState(false);
    const [modalVisible1, setModalVisible1] = useState(false);
    const [list1, setList1] = useState([]);
    let gapStart = 0
    // 用来传当前用户名
    const { user } = useAuth();
    const onFinish = () => {
        setModalVisible(false)
    }
    const onFinish1 = () => {
        setModalVisible1(false)
    }
    const putpinglun = (name, e, id) => {
        // 用来匹配显示评论
        // 评论应该显示在我评论的作品下边
        let id1 = e._dispatchInstances._debugOwner._debugOwner.pendingProps.id
        // console.log(id1);
        if (id == id1) {
            setModalVisible1(!modalVisible1);
            fetch('http://10.7.89.174:3000/fputpinglun', {
                method: 'POST',
                body: JSON.stringify({
                    userName: name,
                    pinglunName: user.userName
                })
            }).then(res => res.json())
                .then(res => {
                    // console.log(res);
                    setList1(res.List)
                    // console.log(list1);
                })
        }

    }
    const post = (name, e, id) => {
        // console.log(name,e,id);
        let id1 = e._dispatchInstances._debugOwner._debugOwner.pendingProps.id
        console.log(id1);
        if (id == id1) {
            setModalVisible(!modalVisible);
        }
        // 用来向数据库提交评论
        fetch('http://10.7.89.174:3000/pinglun',
            {
                method: 'POST',
                // 评论的数据
                body: JSON.stringify({
                    text: text,
                    pinglunName: user.userName,
                    userName: name
                })
            })
            .then(res => res.json())
            .then(res => {
                // console.log(res);
                // setList([...list,...res.List])
                // console.log(list);
            })
    }
    const Chat = (name) => {
        fetch("http://10.7.89.174:3000/fchat", {
            method: "POST",
            body: JSON.stringify({
                userName: user.userName,
                AuserName: name,
            })
        })
            .then(res => res.json())
            .then(res => {
                // console.log(res);
                // 不能跳转
                // console.log(navigation);
                if (res.code == 200 || res.code == 401) {
                    navigation('Chat')
                }
                if (res.code == 400) {
                    alert('就别和自己聊了')
                }
            })
    }
    const addshop = (name, e) => {
        let id1 = e._dispatchInstances._debugOwner._debugOwner.pendingProps.id
        console.log(id1);
        fetch('http://10.7.89.174:3000/addshop', {
            method: "POST",
            body: JSON.stringify({
                shopName: name,
                userName: user.userName,
                id: id1
            })
        })
            .then(res => res.json())
            .then(res => {
                // console.log(res);
                if (res.code == 200) {
                    alert('加入成功')
                }
                else {
                    if (res.code == 400) {
                        alert("购物车已有")
                    } else {
                        alert("加入失败")
                    }
                }
            })
    }
    // 这两个方法没法实现导致不能进行分页
    const onEnd = (e) => {
        // console.log(gapStart,e.timeStamp, gapStart-e.timeStamp);
        if(e.timeStamp - gapStart >= 500 && e.nativeEvent.contentOffset.y + e.nativeEvent.layoutMeasurement.height==e.nativeEvent.contentSize.height) {
            props.children[6](page+1)
        }
    }
    // const onRefresh = () => {
    //     setRefreshing(true);
    //     setPage(1);
    // }
    const renderItem = ({ item }) => (

        <View key={item.saleId} style={{ marginTop: 10 }}>
            {
                btn
                    ? <><View style={{ width: 50, height: 50 }}>
                        <Image source={{ uri: 'data:image/jpeg/jpg;base64,' + item.avatarUrl }}
                            style={{ width: 50, height: 50, borderRadius: 50, marginLeft: 10 }} />
                    </View><Text style={{ marginLeft: 60, marginTop: -40, fontSize: 20, marginLeft: 85 }}>{item.userName}</Text><Text style={{ marginLeft: 380, marginTop: -30, fontSize: 15 }}>
                            {item.saleDate}
                        </Text><View style={{ width: '100%', height: 100 }}>
                            <Text style={{ marginTop: 30, marginLeft: 10 }}>{item.saleText}</Text>
                        </View>
                        {/* 用户上传的图片显示 */}
                        <View style={{ width: 250, height: 250, marginTop: "-5%", marginBottom: '2%' }}>
                            <Image source={{ uri: 'data:image/jpeg/jpg;base64,' + item.base64 }}
                                style={{ width: 250, height: 250, marginLeft: 10 }}
                            ></Image>
                        </View></>
                    : <><View style={{ width: 50, height: 50, marginTop: "5%" }}>
                        {/* 用户头像可以在users中查询，然后把数据放入message中，但是需要一个变量来确定这个用户 */}
                        <Image source={{ uri: 'data:image/jpeg/jpg;base64,' + item.avatarUrl }}
                            style={{ width: 50, height: 50, borderRadius: 50, }} />
                    </View><Text style={{ marginLeft: 60, marginTop: -40, fontSize: 20 }}>{item.userName}</Text><Text style={{ marginLeft: 380, marginTop: -30, fontSize: 15 }}>
                            {item.requestDate}
                        </Text><View style={{ width: '100%', height: 100 }}>
                            <Text style={{ marginTop: 30, marginLeft: 5 }}>{item.requestText}</Text>
                        </View>
                        {/* 用户上传的图片显示 */}
                        <View style={{ width: 250, height: 250, marginTop: "-5%", marginBottom: '2%' }}>
                            <Image source={{ uri: 'data:image/jpeg/jpg;base64,' + item.base64 }}
                                style={{ width: 250, height: 250, marginLeft: 10 }}
                            ></Image>
                        </View></>
            }

            {/* 头像 */}
            {
                // 判断是那个按钮
                btn
                    ? JSON.stringify(user) == "{}"
                        ? (<>
                            <View style={{ flex: 2, flexDirection: "row", marginLeft: 10 }}>
                                {/* 用来操作上传也需要确认点击的按钮，然后调用方法
            这个评论的内容显示的时候需要用到查询，但是通过什么查询 */}
                                <Button title="评论" id={item.saleId} onPress={() => { alert('未登录去登录'); navigation("Login") }} ></Button>
                                <View style={{ marginLeft: 10 }}>
                                    <Button title="显示评论" id={item.saleId} onPress={() => { alert('未登录去登录'); navigation("Login") }} ></Button>
                                </View>
                                <View style={{ marginLeft: 10 }}>
                                    {/* 添加一个后台为了在购物车里有东西
                但是样式有点丑 */}
                                    <Button title="加入购物车" style={{ borderRadius: 100 }} onPress={() => { alert('未登录去登录'); navigation("Login") }}></Button>
                                </View>
                                <View style={{ marginLeft: 10 }}>
                                    {/* 添加一个后台为了在购物车里有东西
                但是样式有点丑 */}
                                    <Button title="跟卖家聊天" style={{ borderRadius: 100 }} onPress={() => { alert('未登录去登录'); navigation("Login") }}></Button>
                                </View>
                            </View>
                        </>)
                        : (<>
                            <View style={{ flex: 2, flexDirection: "row", marginLeft: 10 }}>
                                {/* 用来操作上传也需要确认点击的按钮，然后调用方法
            这个评论的内容显示的时候需要用到查询，但是通过什么查询 */}
                                <Button title="评论" id={item.saleId} onPress={(e) => post(item.userName, e, item.saleId)} ></Button>
                                <View style={{ marginLeft: 10 }}>
                                    <Button title="显示评论" id={item.saleId} onPress={(e) => putpinglun(item.userName, e, item.saleId)} ></Button>
                                </View>
                                <View style={{ marginLeft: 10 }}>
                                    {/* 添加一个后台为了在购物车里有东西
                但是样式有点丑 */}
                                    <Button title="加入购物车" id={item.saleId} style={{ borderRadius: 100 }} onPress={(e) => { addshop(item.userName, e) }}></Button>
                                </View>
                                <View style={{ marginLeft: 10 }}>
                                    {/* 添加一个后台为了在购物车里有东西
                但是样式有点丑 */}
                                    <Button title="跟卖家聊天" style={{ borderRadius: 100 }} onPress={() => { Chat(item.userName); }}></Button>
                                </View>
                            </View>
                        </>)
                    :
                    JSON.stringify(user) == "{}"
                        ?
                        (<>
                            <View style={{ flex: 2, flexDirection: "row", marginTop: '2%' }}>
                                <Button title="评论" id={item.requestId} onPress={() => { alert('未登录去登录'); navigation("Login") }} ></Button>
                                <View style={{ marginLeft: 10 }}>
                                    <Button title="显示评论" id={item.requestId} onPress={() => { alert('未登录去登录'); navigation("Login") }} ></Button>
                                </View>
                                <View style={{ marginLeft: 10 }}>
                                    <Button title="跟买家聊天" style={{ borderRadius: 100 }} onPress={() => { alert('未登录去登录'); navigation("Login") }}></Button>
                                </View>
                            </View>
                        </>)
                        : (<>
                            <View style={{ flex: 2, flexDirection: "row", marginTop: '2%' }}>
                                <Button title="评论" id={item.requestId} onPress={(e) => post(item.userName, e, item.requestId)} ></Button>
                                <View style={{ marginLeft: 10 }}>
                                    <Button title="显示评论" id={item.requestId} onPress={(e) => putpinglun(item.userName, e, item.requestId)} ></Button>
                                </View>
                                <View style={{ marginLeft: 10 }}>
                                    <Button title="跟买家聊天" style={{ borderRadius: 100 }}
                                        onPress={() => { Chat(item.userName) }}
                                    ></Button>
                                </View>
                            </View>
                        </>)
            }
        </View>
    )
    return (
        <View>
            <Modal
                animationType="slide"
                transparent={true}
                visible={modalVisible}
                onRequestClose={() => {
                    setModalVisible(!modalVisible);
                    onFinish
                }}
            >
                <View style={styles.centeredView} >
                    <View style={styles.modalView}>
                        <TextInput
                            placeholder="评论"
                            style={styles.modalText}
                            onChangeText={(text) => { setText(text) }}
                            value={text}
                        ></TextInput>
                        <TouchableHighlight
                            style={styles.openButton}
                            onPress={() => {
                                setModalVisible(!modalVisible);
                            }}
                        >
                            <Button
                                block
                                shape='round'
                                type="primary"
                                htmlType="submit"
                                title="发布评论"
                                onPress={onFinish}
                            >
                            </Button>
                        </TouchableHighlight>
                    </View>
                </View>
            </Modal>
            {/* 用来展示评论 */}
            <Modal
                animationType="slide"
                transparent={true}
                visible={modalVisible1}
                onRequestClose={() => {
                    setModalVisible1(!modalVisible1);
                    onFinish1
                }}
            >
                <View style={styles.centeredView} >
                    <View style={styles.modalView}>
                        <View>
                            {
                                list1.map(item => {
                                    return <View>
                                        <Text>{item["pinglunName"]}</Text>
                                        <Text>
                                            {item["pinglunDate"]}
                                        </Text>
                                        <View>
                                            <Text>{item["pinglun"]}</Text>
                                        </View>
                                    </View>
                                }
                                )
                            }

                        </View>
                        <TouchableHighlight
                            style={styles.openButton}
                            onPress={() => {
                                setModalVisible(!modalVisible1);
                            }}
                        >
                            <Button
                                block
                                type="primary"
                                htmlType="submit"
                                title="关闭评论"
                                onPress={onFinish1}
                                color={"orange"}
                            >
                            </Button>
                        </TouchableHighlight>
                    </View>
                </View>
            </Modal>
            <FlatList
                style={{height:500}}
                ListEmptyComponent={<Text>暂无数据</Text>}
                onRefresh={props.children[5]}
                refreshing={props.children[3]}
                data={props.children[1]}
                renderItem={renderItem}
                onScrollBeginDrag={(e)=>{gapStart = e.timeStamp }}
                onScrollEndDrag={e =>onEnd(e)}
                keyExtractor={item => item.id}
            />
            {
                props.children[1].length == 0
                    ? <View style={{marginTop:"-100%"}}><Text style={{fontSize:20}}>未查询到该内容</Text></View>
                    : <></>
            }
        </View>
    )
}
const styles = StyleSheet.create({
    centeredView: {
        flex: 1,
        justifyContent: "center",
        alignItems: "center",
        marginTop: "30%"
    },
    bgimg: {
        flex: 1,
        resizeMode: "cover",
        justifyContent: "center"
    },
    modalView: {
        width: 300,
        height: "30%",
        margin: 20,
        backgroundColor: "white",
        borderRadius: 20,
        padding: 35,
        alignItems: "center",
        shadowColor: "#000",
        shadowOffset: {
            width: 0,
            height: 2
        },
        shadowOpacity: 0.25,
        shadowRadius: 3.84,
        elevation: 5
    },
    openButton: {
        margin: "auto",
        padding: "8%",

    },
    textStyle: {
        color: "white",
        fontWeight: "bold",
        textAlign: "center"
    },
    modalText: {
        width: 100,
        height: 50,
        marginBottom: 15,
        textAlign: "center"
    }
});
export default Sale